package com.xigege.netty.protocolDesignAndAnalysis.customProtocol.rpc.client;

import com.xigege.netty.protocolDesignAndAnalysis.customProtocol.message.RpcRequestMessage;
import com.xigege.netty.protocolDesignAndAnalysis.customProtocol.protocol.MessageCodecSharable;
import com.xigege.netty.protocolDesignAndAnalysis.customProtocol.rpc.client.handler.RpcResponseMessageHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;

/**
 * @author huangxi
 * @class RpcClient
 * @description 写死的RpcClient，作为一个Demo
 * @create 2022-08-31 12:43
 */
public class RpcClient {
    public static void main(String[] args) {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC_SHARABLE = new MessageCodecSharable();
        RpcResponseMessageHandler RPC_RESPONSE = new RpcResponseMessageHandler();
        try {
            ChannelFuture future = new Bootstrap()
                    .group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 12, 4, 0, 0));
                            ch.pipeline().addLast(LOGGING_HANDLER);
                            ch.pipeline().addLast(MESSAGE_CODEC_SHARABLE);
                            ch.pipeline().addLast(RPC_RESPONSE);
                        }
                    }).connect(new InetSocketAddress(6666));
            Channel channel = future.sync().channel();
            // 连接成功后发送消息
            channel.writeAndFlush(new RpcRequestMessage(
                    1,
                    "com.xigege.netty.protocolDesignAndAnalysis.customProtocol.rpc.service.HelloService",
                    "sayHello",
                    String.class,
                    new Class[]{String.class},
                    new Object[]{"张三"}
            )).addListener(promise -> {
                if (!promise.isSuccess()) {
                    Throwable cause = promise.cause();
                    System.out.println(cause);
                }
            });
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
